<template>
  <view class="verification-container">
    <view class="page-header">
      <view class="header-left" @click="goBack">
        <u-icon name="arrow-left" size="20" color="#333"></u-icon>
        <text>返回</text>
      </view>
      <view class="header-title">实名认证</view>
      <view class="header-right"></view>
    </view>

    <view class="content">
      <view class="form-section">
        <view class="section-title">个人信息</view>

        <view class="form-item">
          <view class="form-label">真实姓名</view>
          <input class="form-input" v-model="formData.realName" placeholder="请输入真实姓名" :disabled="isVerified" />
        </view>

        <view class="form-item">
          <view class="form-label">身份证号</view>
          <input class="form-input" v-model="formData.idCard" placeholder="请输入身份证号码" maxlength="18" :disabled="isVerified" />
        </view>

        <view class="form-item">
          <view class="form-label">手机号码</view>
          <input class="form-input" v-model="formData.phone" placeholder="请输入手机号码" type="number" maxlength="11" :disabled="isVerified" />
        </view>
      </view>

      <view class="form-section">
        <view class="section-title">身份证照片</view>
        <view class="upload-section">
          <view class="upload-item">
            <view class="upload-box" @click="chooseImage('front')" :class="{'disabled': isVerified}">
              <image v-if="formData.idCardFront" :src="formData.idCardFront" class="upload-image" mode="aspectFill"></image>
              <view v-else class="upload-placeholder">
                <u-icon name="camera" size="30" color="#1989fa"></u-icon>
                <text>上传身份证正面</text>
              </view>
            </view>
            <text class="upload-tip">身份证正面</text>
          </view>

          <view class="upload-item">
            <view class="upload-box" @click="chooseImage('back')" :class="{'disabled': isVerified}">
              <image v-if="formData.idCardBack" :src="formData.idCardBack" class="upload-image" mode="aspectFill"></image>
              <view v-else class="upload-placeholder">
                <u-icon name="camera" size="30" color="#1989fa"></u-icon>
                <text>上传身份证背面</text>
              </view>
            </view>
            <text class="upload-tip">身份证背面</text>
          </view>
        </view>
      </view>
      <view class="agreement-section" v-if="!isVerified">
        <checkbox-group  @change="checkboxChange">
          <checkbox color="#1989fa" />
        </checkbox-group>

        <text class="agreement-text">我已阅读并同意<text class="link-text" @click="viewAgreement('register_agreement')">《用户协议》</text>和<text class="link-text" @click="viewAgreement('privacy_agreement')">《隐私政策》</text></text>
      </view>

      <button class="submit-btn" @click="submitVerification" :disabled="isVerified" :class="{'disabled-btn': isVerified}">
        {{ isVerified ? '已完成认证' : '提交认证' }}
      </button>

      <view class="tips-section" v-if="!isVerified">
        <view class="tip-item">
          <u-icon name="info-circle" size="16" color="#999"></u-icon>
          <text class="tip-text">请确保提交的信息真实有效，否则将无法通过审核</text>
        </view>
        <view class="tip-item">
          <u-icon name="info-circle" size="16" color="#999"></u-icon>
          <text class="tip-text">实名认证通过后不可修改，请谨慎填写</text>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
import { mapState, mapActions } from 'vuex'
import { verifyUser } from '@/api/user'
import {apiConfig} from '@/utils/apiConfig'
import { getAccessToken } from '@/utils/auth'

export default {
  data() {
    return {
      formData: {
        realName: '',
        idCard: '',
        phone: '',
        idCardFront: '',
        idCardBack: '',
        agreement: false
      },
      uploading: false,
      loading: false
    }
  },
  computed: {
    ...mapState({
      userInfo: state => state.user.userInfo,
      userVerification: state => state.user.userVerification
    }),
    // 判断用户是否已认证
    isVerified() {
      return this.userInfo && this.userInfo.auth === 1;
    }
  },
  onShow() {
    // 每次显示页面时获取最新的用户信息
    this.getUserInfo();
  },
  onLoad() {
    // 首次加载时获取用户信息
    this.getUserInfo();
  },
  methods: {
    ...mapActions(['GetUserInfo', 'GetUserVerification']),
    checkboxChange(e) {
      console.log(e)
      if(e.detail.value.length == 0){
        this.formData.agreement = false
				}else{
					this.formData.agreement = true
				}
    },
    viewAgreement(type) {
      uni.navigateTo({
        url: '/pages/contract/agreement?type=' + type
      })
    },
    // 获取用户信息
    getUserInfo() {
      if (this.loading) return;

      this.loading = true;
      this.GetUserInfo().then(() => {
        // 如果已经有用户信息，预填充表单
        if (this.userInfo && this.userInfo.id) {
          this.formData.idCard = this.userInfo.idCard || '';

          // 如果已经认证过，显示已有的认证信息，但不允许修改
          if (this.userInfo.auth === 1) {
            this.GetUserVerification().then(() => {
              if (this.userVerification) {
                this.formData.realName = this.userVerification.realName || '';
                this.formData.phone = this.userVerification.phone || '';
                this.formData.idCardFront = this.userVerification.idCardFront || '';
                this.formData.idCardBack = this.userVerification.idCardBack || '';
              }

              // 如果已认证，禁用表单
              this.disableForm();
            }).catch(() => {
              uni.showToast({
                title: '获取认证信息失败',
                icon: 'none'
              });
            });
          }
        }

        this.loading = false;
      }).catch(error => {
        this.loading = false;
        uni.showToast({
          title: '获取用户信息失败',
          icon: 'none'
        });
      });
    },

    // 禁用表单
    disableForm() {
      // 显示已认证提示
      uni.showModal({
        title: '已完成实名认证',
        content: '您已完成实名认证，认证信息不可修改',
        showCancel: false,
        success: () => {
          // 可以选择返回上一页
          // uni.navigateBack();
        }
      });
    },

    goBack() {
      uni.navigateBack();
    },

    chooseImage(type) {
      // 如果已认证，不允许修改
      if (this.isVerified) {
        return uni.showToast({
          title: '已认证信息不可修改',
          icon: 'none'
        });
      }

      uni.chooseImage({
        count: 1,
        sizeType: ['compressed'],
        sourceType: ['album', 'camera'],
        success: (res) => {
          const tempFilePath = res.tempFilePaths[0];
          const files = res.tempFiles[0]
          // 上传图片到服务器
          this.uploadImage(tempFilePath, type);
        }
      });
    },

    uploadImage(filePath, type) {
      if (this.uploading) {
        return uni.showToast({
          title: '正在上传中，请稍候',
          icon: 'none'
        });
      }

      this.uploading = true;
      uni.showLoading({
        title: '上传中...'
      });

      uni.uploadFile({
        timeout: 10000,
        url: apiConfig.baseUrl + '/app-api/infra/file/upload',
        filePath: filePath,
        name: 'file',
        header: {
          'Authorization': 'Bearer ' + getAccessToken(),
          'tenant-id': apiConfig.tenantId
        },
        method: 'post',
        success: (uploadRes) => {
          console.log(uploadRes);
          try {
            const data = JSON.parse(uploadRes.data);
            console.log(data)
            console.log(data.data)
            console.log(data.data.url)
            if (data.code === 0 && data.data) {
              // 上传成功，保存图片URL
              if (type === 'front') {
                this.formData.idCardFront = data.data;
              } else {
                this.formData.idCardBack = data.data;
              }

              uni.showToast({
                title: '上传成功',
                icon: 'success'
              });
            } else {
              uni.showToast({
                title: data.msg || '上传失败',
                icon: 'none'
              });
            }
          } catch (e) {
            uni.showToast({
              title: '上传失败',
              icon: 'none'
            });
          }
        },
        fail: () => {
          uni.showToast({
            title: '上传失败',
            icon: 'none'
          });
        },
        complete: () => {
          this.uploading = false;
          uni.hideLoading();
        }
      })
    },
    checkIdNumber(idNumber) {
        // 正则表达式验证身份证格式
        const reg = /^(?:\d{15}|\d{17}[\dX])$/;
        if (!reg.test(idNumber)) {
            console.error('身份证号码格式不正确');
            return false;
        }

        // 如果是18位身份证，进行校验位验证
        if (idNumber.length === 18) {
            const weights = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2];
            const checkDigits = '10X98765432';
            let sum = 0;

            for (let i = 0; i < 17; i++) {
                sum += idNumber[i] * weights[i];
            }

            const checkDigit = checkDigits[sum % 11];
            if (checkDigit !== idNumber[17]) {
                console.error('身份证号码校验位不正确');
                return false;
            }
        }

        console.log('身份证号码有效');
        return true;
    },
    checkPhoneNumber(phoneNumber) {
        // 正则表达式验证手机号格式
        const reg = /^1[3-9]\d{9}$/;
        if (!reg.test(phoneNumber)) {
            console.error('手机号格式不正确');
            return false;
        }

        console.log('手机号有效');
        return true;
    },

    submitVerification() {
      // 如果已认证，不允许提交
      if (this.isVerified) {
        return uni.showToast({
          title: '您已完成实名认证',
          icon: 'none'
        });
      }

      // 表单验证
      if (!this.formData.realName) {
        return uni.showToast({
          title: '请输入真实姓名',
          icon: 'none'
        });
      }

      if (!this.formData.idCard || !this.checkIdNumber(this.formData.idCard)) {
        return uni.showToast({
          title: '请输入正确的身份证号',
          icon: 'none'
        });
      }

      if (!this.formData.phone || !this.checkPhoneNumber(this.formData.phone)) {
        return uni.showToast({
          title: '请输入正确的手机号',
          icon: 'none'
        });
      }

      if (!this.formData.idCardFront) {
        return uni.showToast({
          title: '请上传身份证正面照片',
          icon: 'none'
        });
      }

      if (!this.formData.idCardBack) {
        return uni.showToast({
          title: '请上传身份证背面照片',
          icon: 'none'
        });
      }
      console.log(this.formData)
      if (!this.formData.agreement) {
        return uni.showToast({
          title: '请阅读并同意用户协议',
          icon: 'none'
        });
      }

      // 提交认证
      uni.showLoading({
        title: '提交中...'
      });

      // 调用实名认证接口
      verifyUser({
        "realName": this.formData.realName,
        "idCard": this.formData.idCard,
        "phone": this.formData.phone,
        "idCardFront": this.formData.idCardFront,
        "idCardBack": this.formData.idCardBack
      }).then(res => {
        uni.hideLoading();

        if (res.data.code === 0) {
          // 认证成功，重新获取用户信息
          this.GetUserInfo().then(() => {
            uni.showModal({
              title: '提交成功',
              content: res.data.data || '您的实名认证信息已提交，请等待审核',
              showCancel: false,
              success: () => {
                uni.navigateBack();
              }
            });
          });
        } else {
          uni.showModal({
            title: '认证失败',
            content: res.data.msg || '提交认证信息失败，请稍后重试',
            showCancel: false
          });
        }
      }).catch(() => {
        uni.hideLoading();
        uni.showModal({
          title: '认证失败',
          content: '网络异常，请稍后重试',
          showCancel: false
        });
      });
    }
  }
}
</script>

<style lang="scss">
.verification-container {
  min-height: 100vh;
  background-color: #f7f7f7;
}

.page-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  height: 90rpx;
  background-color: #fff;
  padding: 0 30rpx;
  border-bottom: 1px solid #f0f0f0;
}

.header-left {
  display: flex;
  align-items: center;
}

.header-left text {
  margin-left: 10rpx;
  font-size: 28rpx;
  color: #333;
}

.header-title {
  font-size: 32rpx;
  font-weight: 500;
  color: #333;
}

.header-right {
  width: 60rpx;
}

.content {
  padding: 30rpx;
}

.form-section {
  background-color: #fff;
  border-radius: 12rpx;
  padding: 30rpx;
  margin-bottom: 30rpx;
  box-shadow: 0 2rpx 10rpx rgba(0,0,0,0.05);
}

.section-title {
  font-size: 30rpx;
  font-weight: 500;
  color: #333;
  margin-bottom: 30rpx;
  border-left: 4rpx solid #1989fa;
  padding-left: 20rpx;
}

.form-item {
  margin-bottom: 30rpx;
}

.form-label {
  font-size: 28rpx;
  color: #333;
  margin-bottom: 15rpx;
}

.form-input {
  height: 80rpx;
  background-color: #f9f9f9;
  border-radius: 8rpx;
  padding: 0 20rpx;
  font-size: 28rpx;
  color: #333;
}

.upload-section {
  display: flex;
  justify-content: space-between;
}

.upload-item {
  width: 48%;
}

.upload-box {
  height: 200rpx;
  background-color: #f9f9f9;
  border-radius: 8rpx;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  margin-bottom: 10rpx;
  border: 1px dashed #ddd;
}

.upload-placeholder {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.upload-placeholder text {
  font-size: 24rpx;
  color: #999;
  margin-top: 10rpx;
}

.upload-image {
  width: 100%;
  height: 100%;
  border-radius: 8rpx;
}

.upload-tip {
  font-size: 24rpx;
  color: #999;
  text-align: center;
}

.agreement-section {
  display: flex;
  align-items: center;
  margin: 30rpx 0;
}

.agreement-text {
  font-size: 26rpx;
  color: #666;
  margin-left: 10rpx;
}

.link-text {
  color: #1989fa;
}

.submit-btn {
  height: 90rpx;
  background-color: #1989fa;
  color: #fff;
  font-size: 30rpx;
  font-weight: 500;
  border-radius: 45rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  margin: 30rpx 0;
}

.tips-section {
  margin-top: 30rpx;
}

.tip-item {
  display: flex;
  align-items: flex-start;
  margin-bottom: 15rpx;
}

.tip-text {
  font-size: 24rpx;
  color: #999;
  margin-left: 10rpx;
  flex: 1;
}

// 添加禁用样式
.disabled {
  opacity: 0.6;
  pointer-events: none;
}

.disabled-btn {
  background-color: #cccccc !important;
  color: #666666 !important;
}
</style>
